package com.zhiy.com.estation.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhiy.com.estation.Broadcast;
import com.zhiy.com.estation.R;
import com.zhiy.com.estation.fragmentTag.FragmentTag;
import com.zhiy.com.estation.model.User;
import com.zhiy.com.estation.ui.base.BaseFragment;
import com.zhiy.com.estation.ui.fragment.updata.UpdataContract;
import com.zhiy.com.estation.ui.fragment.updata.UpdataModel;
import com.zhiy.com.estation.ui.fragment.updata.UpdataPresent;
import com.zhiy.com.estation.ui.fragment.upload.UploadAvarContract;
import com.zhiy.com.estation.ui.fragment.upload.UploadModel;
import com.zhiy.com.estation.ui.fragment.upload.UploadPresent;
import com.zhiy.com.estation.utils.ImageTools;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class Fragment_Me extends BaseFragment implements UpdataContract.View ,UploadAvarContract.View{
    final int REQUEST_CODE1=1;
    final int REQUEST_CODE2=2;
    @BindView(R.id.per_avar)
    ImageView avar;
//    @BindView(R.id.per_avar)
//    MyCycleImageView avar1;

    @OnClick({R.id.login_state, R.id.back_login})
    public void setPersonInfo(View view) {
        switch (view.getId()) {
            case R.id.login_state:
                if (mPreferen.getAutoLogin()) {
                    //设置头像的操作
                    //跳转到图库进行挑选照片的操作
                    Toast.makeText(mContext, "添加设置头像的操作", Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent(Intent.ACTION_PICK,null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                    mBaseActivity.startActivityForResult(intent,REQUEST_CODE1);
                } else {
                    mBaseActivity.showFragment(Fragment_Login.class, FragmentTag.LOGIG, null, true);
                }
                break;
            case R.id.back_login:
                //广播必须得反注册否则会报错
                mBaseActivity.unregisterReceiver(receiver);
                mPreferen.saveToAutoLogin(false);
                mBaseActivity.finish();
                break;
        }

    }
    //自定义的动作
    public void startPhotoZoom(Uri uri){
        //跳转图片剪裁的页面，自定义的动作使用的时候要加上包名前缀
        Intent intent=new Intent("com.android.camera.action.CROP");//这个动作是裁剪的动作
        intent.setDataAndType(uri,"image/*");//URI是已经选择图片的URI，就是intent动作所要操作的数据，Android是通过数据指向来实现的
        intent.putExtra("cope",true);
        intent.putExtra("aspectX",1);//X的剪裁的比例
        intent.putExtra("aspectY",1);//y的剪裁的比例
        intent.putExtra("outputX",300);//剪裁得到的图片的大小
        intent.putExtra("outputY",300);//剪裁得到的图片的大小
        intent.putExtra("return-data",true);//代表着返回数据
        intent.putExtra("noFaceDetection",true);
        mBaseActivity.startActivityForResult(intent,REQUEST_CODE2);//当我们调用这个方法的时候我们自定义个页面就弹出来了
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case REQUEST_CODE1:
                Toast.makeText(mContext, "第一次跳转", Toast.LENGTH_SHORT).show();
//                data.getData()--这里返回的是data的uri
                if (data==null||data.getData()==null){
                    Toast.makeText(mContext, "数据为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                startPhotoZoom(data.getData());
                break;
            case REQUEST_CODE2:
                if (data!=null){
                    Bundle extras=data.getExtras();//获取bundle
                    if (extras!=null){
                        Bitmap photo=extras.getParcelable("data");
                        //系统返回给我们的数据都放在data键下
                        avar.setImageBitmap(photo);
                        //这里进行上传头像的操作
                        uploadAvar(photo);
//                        avar1.setBitmap(photo);
                    }
                }else {
                    Intent intent=new Intent(Intent.ACTION_PICK,null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                    mBaseActivity.startActivityForResult(intent,REQUEST_CODE1);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }
    private void uploadAvar(Bitmap bitmap) {
        //保存图片到sd卡中
        File mFile=ImageTools.savePhotoToSDCard(bitmap,"avar.png");
        UploadPresent presenter=new UploadPresent();
        presenter.setMV(new UploadModel(),this);
        presenter.upload(mPreferen.getUserid()+"",RequestBody.create(MediaType.parse("image.png"),mFile));
    }

    @Override
    protected int getInflaterLayoutId() {
        return R.layout.fra_person;
    }

    @BindView(R.id.fra_person_list)
    ListView mListView;
    private List<String> data;
    @BindView(R.id.fra_login_state)
    TextView mLoginState;
    private Broadcast receiver;
    @Override
    protected void initView(View view) {
        //注册一个广播
        IntentFilter filter = new IntentFilter(RECEIVER);
        receiver = new Broadcast(new Broadcast.OnLoginListener() {
            @Override
            public void setLoginState() {
                setPersonInfos();
            }
        });
        mBaseActivity.registerReceiver(receiver, filter);
        if (mPreferen.getAutoLogin()) {
            setPersonInfos();

        } else {
            return;
        }
    }

    ItemtClickLisner mItemtClickLisner;
    private AlertDialog.Builder builder;

    @Override
    public void isUpdataSuccess(User user) {
        //保存用户的信息
        String name=user.getName();
        String phone=user.getPhone();
        String email=user.getEmail();
        if (name!=null){
            mPreferen.saveToName(name);
        }
       if (email!=null){
           mPreferen.saveToEmail(email);
       }
        if (phone!=null){
            mPreferen.saveToPhone(phone);
        }
        data.clear();
        data.add(name);
        data.add(email);
        data.add(phone);
        myAdapter.notifyDataSetChanged();
    }

    @Override
    public void isSuccess(String avar) {
        mPreferen.saveToavar(avar);//保存网上的图片的路径，使用Glide设置图片
    }
    @Override
    public void isFailure() {

    }

    @Override
    public void showMsg(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    class ItemtClickLisner implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (builder == null) {
                builder = new AlertDialog.Builder(mBaseActivity);
                mListener = new OnDialogListener();
            }
            myAdapter.holder = (MyAdapter.ViewHolder) view.getTag();
            builder.setTitle("是要设置" + myAdapter.holder.avar.getText().toString());
            View view1 = LayoutInflater.from(mContext).inflate(R.layout.updata_info, null);
            infoEt = (EditText) view1.findViewById(R.id.updata_info_et);
            builder.setView(view1);
            builder.setPositiveButton("确认", mListener);
            builder.setNegativeButton("取消", mListener);
            builder.create().show();
        }
    }

    EditText infoEt;
    String info;
    HashMap<String, String> map = new HashMap<>();
    OnDialogListener mListener;

    class OnDialogListener implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (!TextUtils.isEmpty(infoEt.getText().toString())){
                info = infoEt.getText().toString();
                map.put("userid", mPreferen.getUserid() + "");
                switch (myAdapter.holder.avar.getText().toString()){
                    case "用户名":
                        map.put("name",info);
                        break;
                    case "邮箱":
                        map.put("email",info);
                        break;
                    case "电话":
                        map.put("phone",info);
                        break;
                    default:
                        break;
                }
                Log.d("----------", "onClick: " + map.toString());
                UpdataPresent present = new UpdataPresent();
                present.setMV(new UpdataModel(), Fragment_Me.this);
                Log.d("----------", "onClick: " + map.toString());
                present.updata(map);
            }
        }
    }


    private MyAdapter myAdapter;

    private void setPersonInfos() {
        mLoginState.setText("已登录");
        myAdapter = new MyAdapter();
        data = new ArrayList<>();
        data.add(mPreferen.getName());
        data.add(mPreferen.getEmail());
        data.add(mPreferen.getPhone());
        mListView.setAdapter(myAdapter);
        mItemtClickLisner = new ItemtClickLisner();
        mListView.setOnItemClickListener(mItemtClickLisner);
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public String getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.item_fra_person, null);
                holder = new ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            switch (i) {
                case 0:
                    holder.avar.setText("用户名");
                    break;
                case 1:
                    holder.avar.setText("邮箱");
                    break;
                case 2:
                    holder.avar.setText("电话");
                    break;
            }

            holder.msgEt.setText(getItem(i));
            return view;
        }

        ViewHolder holder;

        class ViewHolder {
            TextView avar;
            TextView msgEt;

            public ViewHolder(View view) {
                avar = (TextView) view.findViewById(R.id.avar);
                msgEt = (TextView) view.findViewById(R.id.per_msg);
            }
        }
    }

    @Override
    public void onDestroy() {
        mBaseActivity.unregisterReceiver(receiver);
        super.onDestroy();


    }
}
